#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from sqlalchemy import desc, func
from sqlalchemy.orm import Session

from backend.app.model import Category
from backend.app.schema.category import CreateCategory


def get_category(db: Session) -> bool:
    return db.query(Category)


def get_categories(db: Session, category_id: int, page: int, limit: int) -> list:
    return db.query(Category).filter(Category.id == category_id).order_by(Category.last_mod_time.desc()).\
        limit(limit).offset((page - 1) * limit).all()


def get_category_for_id(db: Session, category_id: int) -> Category:
    return db.query(Category).get(category_id)


def get_category_by_id(db: Session, category_id: int) -> bool:
    return db.query(Category).filter(Category.id == category_id).first()


def get_category_by_name(db: Session, category_name: str) -> bool:
    return db.query(Category).filter(Category.name == category_name).first()


def create_category(db: Session, post: CreateCategory) -> Category:
    category_obj = Category(**post.dict())
    db.add(category_obj)
    db.commit()
    db.refresh(category_obj)
    return category_obj


def update_category(db: Session, category_id: int, put: CreateCategory) -> bool:
    cate = db.query(Category).filter(Category.id == category_id)
    cate.update({'name': put.name, 'last_mod_time': func.now()})
    db.commit()
    return cate.first()


def delete_category(db: Session, category_id: int) -> bool:
    cate = db.query(Category).filter(Category.id == category_id)
    cate.delete()
    db.commit()
    return cate.first()
